<template>
  <div class="move-line" :style="{ left, height }" ref="lineRef" @mousedown="mousedown"></div>
</template>

<script setup name="MoveLine">
const { left } = defineProps({
  left: { type: String, default: '0' },
  height: { type: String, default: '0' },
});
const leftRef = ref(null);
const lineRef = ref(null);
const state = reactive({
  resizing: false,
  beginX: 0,
  startLeft: 0,
  startWidth: 0,
});
onMounted(() => {
  lineRef.value.parentElement.addEventListener('mousemove', mousemove);
  lineRef.value.parentElement.addEventListener('mouseup', mouseup);
});
onBeforeUnmount(() => {
  lineRef.value.parentElement.removeEventListener('mousemove', mousemove);
  lineRef.value.parentElement.removeEventListener('mouseup', mouseup);
});
// 拖动事件
const mousedown = (e) => {
  e.preventDefault();
  leftRef.value = e.target.previousElementSibling;
  state.startWidth = parseFloat(getComputedStyle(leftRef.value).width);
  state.resizing = true;
  state.beginX = e.clientX;
  state.startLeft = getComputedStyle(e.target).left;
};
const mousemove = (e) => {
  if (!state.resizing) return;
  const x = e.clientX - state.beginX;
  lineRef.value.style.left = `${parseFloat(state.startLeft) + x}px`;
};
const mouseup = (e) => {
  if (!state.resizing) return;
  const x = e.clientX - state.beginX;
  leftRef.value.style.width = `${state.startWidth + x}px`;
  state.resizing = false;
};
</script>

<style lang="less" scoped>
.move-line {
  position: absolute;
  z-index: 1;
  width: 10px;
  bottom: 0;
  border-left: 1px solid var(--el-border-color-light);
  &:hover {
    cursor: col-resize;
  }
}
</style>
